import 'package:flutter/material.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter_deer/account/account_router.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/shop/iview/agent_user_iview.dart';
import 'package:flutter_deer/shop/models/agent_user_entity.dart';
import 'package:flutter_deer/shop/presenter/agent_user_presenter.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/widgets/fadein_text.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/my_card.dart';
import 'package:flutter_deer/account/widgets/rise_number_text.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/shop/provider/agent_user_provider.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';

class AgentListPage extends StatefulWidget {

  const AgentListPage({super.key,required this.agentUser});

  final bool? agentUser;

  @override
  _AgentPageState createState() => _AgentPageState();
}

class _AgentPageState extends State<AgentListPage> with BasePageMixin<AgentListPage, AgentUserPagePresenter>, AutomaticKeepAliveClientMixin<AgentListPage> implements AgentUserIMvpView {
  
  final ScrollController _scrollController = ScrollController();

  AgentUserProvider provider = AgentUserProvider();

  bool get wantKeepAlive => true;
  @override
  AgentUserPagePresenter createPresenter() => AgentUserPagePresenter();
  @override
  void setAgentUserList(List<AgentUserEntity>? agentUsers){
    provider.setAgentUserList(agentUsers);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    provider.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: '${DeerLocalizations.of(context)!.subordinate.nullSafe}'
      ),
      body: ChangeNotifierProvider<AgentUserProvider>(
        create: (_) => provider,
        child: SingleChildScrollView(
          child: Consumer<AgentUserProvider>(
            builder: (_,provider,child){
              if(provider.stateType==StateType.loading){
                return StateLayout(type: StateType.loading);
              }
              if(provider.empty==true){
                return Container(
                  width: MediaQuery.of(context).size.width,
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Gaps.vGap5,
                        _buildCard(provider.totalMoney,provider.totalUsers),
                        Gaps.vGap5,
                        Gaps.vGap50,
                        LoadAssetImage('account/agent_user_group',format: ImageFormat.gif,),
                        Gaps.vGap16,
                        FadeInText(text: '${DeerLocalizations.of(context)!.noSubordinateUsers.nullSafe}')
                      ],
                    ),
                  ),
                );
              }
              return ListView.builder(
                  itemCount: provider.empty==true?2:provider.agentUserList!.length+1,
                  shrinkWrap: true,
                  physics: new NeverScrollableScrollPhysics(),
                  padding: const EdgeInsets.only(left: 12.0, right: 12.0, bottom: 28.0),
                  itemBuilder: (BuildContext context, int index) {
                    if(index==0){
                      return Column(
                          children: <Widget>[
                            Gaps.vGap5,
                            _buildCard(provider.totalMoney,provider.totalUsers),
                            Gaps.vGap5
                          ]
                      );
                    }else{
                      if(provider.empty==true&&index==1){
                        return Container(
                        );
                      }
                      return _AgentItem(provider.agentUserList!.elementAt(index-1),widget.agentUser);
                    }
                  }
              );
            }
          )
        )
      )
    );
  }

  Widget _buildCard(double? totalMoney,int? totalUsers) {
    return AspectRatio(
      aspectRatio: 2.55,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 6.0),
        padding: const EdgeInsets.all(6.0),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: ImageUtils.getAssetImage('account/bg'),
            fit: BoxFit.fill,
          ),
        ),
        child: Row(
          children: <Widget>[
            _AccountAgent(title: '${DeerLocalizations.of(context)!.accumulatedRewards.nullSafe}', count: '${totalMoney}',countFormat:'double'),
            _AccountAgent(title: '${DeerLocalizations.of(context)!.totalSubordinates.nullSafe}', count: '${totalUsers}',countFormat:'int'),
          ]
        )
      )
    );
  }

}

class _AgentItem extends StatefulWidget {

  _AgentItem(this.agentUserEntity,this.isAgent);

  AgentUserEntity? agentUserEntity;
  bool? isAgent;

  @override
  _AgentItemState createState() => _AgentItemState();
}

class _AgentItemState extends State<_AgentItem> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        if(widget.isAgent==true){
          NavigatorUtils.push(context, AccountRouter.belowUserScorePage,arguments: widget.agentUserEntity!.belowUsername.nullSafe);
        }
      },
      child: Padding(
          padding: EdgeInsets.only(top: 5.0,bottom: 5.0),
          child: MyCard(
                  child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10.0),
                      child: Column(
                          children: <Widget>[
                            Row(
                                children: <Widget>[
                                  CircleAvatar(radius: 24.0,backgroundColor: Colors.transparent,backgroundImage: ImageUtils.getImageProvider(Constant.imageServerHost+'${widget.agentUserEntity!.belowAvatar}', holderImg: 'shop/tx')),
                                  Gaps.hGap8,
                                  Text('${DeerLocalizations.of(context)!.playerAccount.nullSafe}:${widget.agentUserEntity!.belowAccountId}')
                                ]
                            ),
                            Gaps.vGap8,
                            Visibility(child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('${DeerLocalizations.of(context)!.accumulatedRecharge.nullSafe}:${widget.agentUserEntity!.totalDepositScore}'),
                                  Text('${DeerLocalizations.of(context)!.accumulatedWithdraw.nullSafe}:${widget.agentUserEntity!.totalTakeOutScore}'),
                                ]
                            ),visible: widget.isAgent!,),
                            Visibility(child: Gaps.vGap8,visible: widget.isAgent!,),
                            Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('${DeerLocalizations.of(context)!.registerTime.nullSafe}:${widget.agentUserEntity!.createTime}'),
                                  Text('${DeerLocalizations.of(context)!.rewardAmount.nullSafe}:${widget.agentUserEntity!.winScore}'),
                                ]
                            ),
                            Gaps.vGap5
                          ]
                      )
                  )
              )
          )

    );
  }
}

class _AccountAgent extends StatelessWidget {
  
  const _AccountAgent({
    required this.title,
    required this.count,
    required this.countFormat,
    this.alignment,
    this.moneyTextStyle
  });

  final String title;
  final String count;
  final String countFormat;
  final MainAxisAlignment? alignment;
  final TextStyle? moneyTextStyle;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: MergeSemantics(
        child: Column(
          mainAxisAlignment: alignment ?? MainAxisAlignment.center,
          children: <Widget>[
            /// 横向撑开Column，扩大语义区域
            const SizedBox(width: double.infinity),
            Text(title, style: const TextStyle(color: Colours.text_disabled, fontSize: Dimens.font_sp14)),
            Gaps.vGap8,
            countFormat=='double'?
            RiseNumberText(
              NumUtil.getDoubleByValueStr(count) ?? 0,
              style: moneyTextStyle ?? const TextStyle(
                color: Colours.text_disabled, 
                fontSize: Dimens.font_sp14,
                fontWeight: FontWeight.bold,
                fontFamily: 'RobotoThin'
              )
            ):Text(count,style: moneyTextStyle ?? const TextStyle(
                color: Colours.text_disabled, 
                fontSize: Dimens.font_sp14,
                fontWeight: FontWeight.bold,
                fontFamily: 'RobotoThin'
              )
            )
          ],
        ),
      ),
    );
  }
}
